<template>
  <div id="my_articles">
    <Layout>
      <Content>
        <div v-if="!articles.length" id="empty">咦，这里是空的哎</div>
        <List border>
          <ListItem v-for="article in articles" :key="article.id">
            <router-link
              :to="'view/'+article.id"
            >{{article.title}} ({{formatDate(article.create_date_time)}})</router-link>
          </ListItem>
        </List>
      </Content>
      <Footer>
        <Page
          :total="total_num"
          :page-size="page_size"
          :current.sync="current_page"
          @on-change="changePage"
          show-elevator
        />
      </Footer>
    </Layout>
  </div>
</template>

<script>
export default {
  name: "MyArticles",
  data() {
    return {
      articles: [],
      current_page: 1,//当前页
      total_num: 0,//数据总数
      page_size: 20,//每页条数
    };
  },
  created: function () {
    this.getArticlesNum();
    this.getArticles();
  },
  methods: {
    formatDate(UTCDateString) {
      if (!UTCDateString) {
        return "-";
      }
      function formatFunc(str) {
        //格式化显示
        return str > 9 ? str : "0" + str;
      }
      var date2 = new Date(UTCDateString); //这步是关键
      var year = date2.getFullYear();
      var mon = formatFunc(date2.getMonth() + 1);
      var day = formatFunc(date2.getDate());
      var hour = formatFunc(date2.getHours());
      var minute = formatFunc(date2.getMinutes());
      var second = formatFunc(date2.getSeconds());
      var dateStr =
        year + "-" + mon + "-" + day + " " + hour + ":" + minute + ":" + second;
      return dateStr;
    },
    getArticlesNum() {
      this.$api.get("myarticlenum/", {}, (response) => {
        if (response.status == 200) {
          var data = response.data;
          if (data.err_code == 0) {
            data = data.data;
            this.total_num = data;
          } else {
            this.$Message.error(data.error);
          }
        } else {
          this.$Message.error("抱歉，发生错误");
          this.$Message.error("" + response);
        }
      });
    },
    getArticles() {
      this.$api.get(
        "myarticles/",
        {
          start: this.page_size * (this.current_page - 1) + 1,
          end: this.page_size * this.current_page,
        },
        (response) => {
          if (response.status == 200) {
            var data = response.data;
            if (data.err_code == 0) {
              data = data.data;
              this.articles = data;
            } else {
              this.$Message.error(data.error);
            }
          } else {
            this.$Message.error("抱歉，发生错误" + response);
          }
        }
      );
    },
    changePage() {
      this.getArticles();
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#empty {
  font-size: 15px;
  margin: 20px;
}
</style>
